;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GiftOut", [])
        .controller("GiftOutCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "MaterialService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, MaterialService, $stateParams) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.submitted = false;
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.orderCondition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.giftBillList = [];
            $scope.detailInfo = {
                headInfo: {},
                details: [],
            };
            $scope.steps = {
                curStep: 0,
                list: [{
                    name: '选择兑换订单'
                }, {
                    name: '生成兑换出库单'
                }]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/giftticket/exchangeOut/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/giftticket/exchangeOut/exportAll")
            };
            $scope.outState = [{
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                },
                {
                    id: 3,
                    name: "强制结单"
                }
            ];
            $scope.tableConfig = {
                fixedWidth: 220,
                scrollWidth: 1400,
                tableCol: [{
                        type: "",
                        name: "出库单号",
                        dataField: "exchangeOutNo",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "兑换订单",
                        dataField: "exchangeNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outboundDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发出仓库",
                        dataField: "outLocation",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "总价",
                        dataField: "totalPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 220,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.giftBillTbConf = {
                scrollWidth: 830,
                tableCol: [{
                        type: "",
                        name: "兑换订单号",
                        dataField: "exchangeNo",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "createTimeShow",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 1120,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单数量",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "issuedQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次发货",
                        width: 100,
                        dataField: "deliveryQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价 ",
                        width: 180,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可用库存",
                        width: 100,
                        dataField: "enableNum",
                        input: false,
                        clickFn: "enableNumDetail",
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "realStockQty",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "shipOccupation",
                        input: false,
                        clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentOccupation",
                        input: false,
                        clickFn: "intentionDetail",
                        inputType: ""
                    },
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 1200,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单数量",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "issuedQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次发货",
                        width: 100,
                        dataField: "deliveryQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价 ",
                        width: 180,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可用库存",
                        width: 100,
                        dataField: "enableNum",
                        input: false,
                        // clickFn: "enableNumDetail",
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "realStockQty",
                        // clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "shipOccupation",
                        input: false,
                        // clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentOccupation",
                        input: false,
                        // clickFn: "intentionDetail",
                        inputType: ""
                    },
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 1300,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        dataField: "locationCode",
                        width: 150,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单数量",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "issuedQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次发货",
                        width: 100,
                        dataField: "deliveryQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价 ",
                        width: 180,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可用库存",
                        width: 100,
                        dataField: "enableNum",
                        input: false,
                        clickFn: "enableNumDetail",
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "realStockQty",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "shipOccupation",
                        input: false,
                        clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentOccupation",
                        input: false,
                        clickFn: "intentionDetail",
                        inputType: ""
                    },
                ]
            };

            $scope.outTbConf = {
                scrollWidth: 1560,
                tableCol: [{
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库存储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        input: true,
                        inputType: "func"
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单数量",
                        dataField: "applyQty",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "issuedQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "deliveryQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "deliveryQty",
                        sortType: "",
                        isInput: true
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "price",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "price",
                        sortType: "",
                        isInput: false
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "realStockQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortField: 'intentOccupation',
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "shipOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "shipOccupation",
                        sortType: ""
                    },
                ]
            };
            $scope.tabFlag = {};

            var btnPermissionCode = {
                giftOutAdd: window.ActionCode.giftOutAdd,
                giftOutEdit: window.ActionCode.giftOutEdit,
                giftOutDel: window.ActionCode.giftOutDel,
                giftOutPrint: window.ActionCode.giftOutPrint,
                giftOutExport: window.ActionCode.giftOutExport,
                giftOutFinish: window.ActionCode.giftOutFinish,
                giftOutOutStock: window.ActionCode.giftOutOutStock,
            };

            $scope.btnPermission = {
                giftOutAdd: true,
                giftOutEdit: true,
                giftOutDel: true,
                giftOutPrint: true,
                giftOutExport: true,
                giftOutFinish: true,
                giftOutOutStock: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };
            var materialList = [];

            function initData() {
                $scope.detailInfo = {
                    headInfo: {},
                    details: [],
                    // allCheckedMaterial: false
                };
                $scope.toolbarConfig.showMateriel = false;
                $scope.steps.curStep = 0;
                $scope.tabFlag = {};
                materialList = [];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/giftticket/exchangeOut/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createTimeShow = $filter("YbDate")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        item.outboundStatusShow = $filter("ProgressStatus")(item.outboundStatus, "outDepot");
                        item.outboundDateShow = $filter("YbDate")(item.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                        // case "alterReport":
                        //     alterReport(item);
                        //     break;
                        // case "intentionDetail":
                        //     intentionDetail(item);
                        //     break;
                        // case "deliveryDetail":
                        //     deliveryDetail(item);
                        //     break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: true
                };
            };

            $scope.addReset = function () {
                $scope.orderCondition = {};
            };

            function geBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                geBillIds();
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                geBillIds();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.add = function () {
                $scope.editDataId = null;
                $scope.tabFlag.type = 0;
                getGuaranteesBill(1);
                $scope.changeTab(1);
            };

            /* ------------------------新增编辑页面--------------------------- */

            /* 1、选择兑换订单创建兑换出库单 */
            function getGuaranteesBill(curPage) {
                var service = "device";
                var reqUrl = "/giftticket/exchangeOut/exchangesQuery";
                var param = {};
                param.pageSize = $scope.billPageInfo.pageSize;
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = {};
                param.filters = $scope.orderCondition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createTimeShow = $filter("YbDate")(item.createTime);
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.giftBillList = resp.value.list;
                });
            }

            $scope.orderSearch = function () {
                getGuaranteesBill();
            };

            $scope.selBill = function (item) {
                $scope.steps.curStep = 1;
                $scope.detailInfo.headInfo = {};
                $scope.detailInfo.details = [];
                ybHttp.Get('device', '/giftticket/exchangeOut/exchangeInfo', {
                    exchangeNo: item.exchangeNo
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.headInfo = resp.value.headInfo;
                    angular.forEach(resp.value.details, function (item) {
                        if (item.enableNum <= 0)  return
                        if (item.applyQty > item.enableNum) {  //判断订单是否大于库存 决定出库数量
                            item.deliveryQty = item.enableNum
                        }else if(item.applyQty < item.enableNum){
                            item.deliveryQty = item.applyQty
                            }               
                        var materielItem = {};
                        materielItem.materialsNo = item.materialsNo;
                        materielItem.materialsDes = item.materialsDes;
                        materielItem.unit = item.unit;
                        materielItem.price = item.price;
                        materielItem.applyQty = item.applyQty;
                        materielItem.issuedQty = item.issuedQty;
                        materielItem.deliveryQty = item.deliveryQty;
                        materielItem.realStockQty = item.realStockQty;
                        materielItem.shipOccupation = item.shipOccupation;
                        materielItem.enableNum = item.enableNum;
                        materielItem.intentOccupation = item.intentOccupation;
                        materielItem.stockLocationList = item.stockLocationList;
                        materielItem.lastQty = ybWidget.Minus(item.applyQty, item.deliveryQty);
                        
                        $scope.detailInfo.details.push(materielItem);
                        // }
                    });
                    materialList = angular.copy($scope.detailInfo.details);
                });
            };

            $scope.selectSingleMeal = function (item) {
                var selectAll = false;
                if (!!item.isChecked) {
                    item.isChecked = true;
                } else {
                    item.isChecked = false;
                }
                for (var i = 0, len = $scope.detailInfo.details.length; i < len; i++) {
                    if (!$scope.detailInfo.details[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                $scope.detailInfo.allCheckedMaterial = selectAll;
            };

            $scope.selectAllMeal = function (list) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.detailInfo.allCheckedMaterial;
                });

            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/salesBill/download",
                    importReqService: "device",
                    importReqUrl: "/salesBill/import",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.detailInfo.details = [];
                    $scope.detailInfo.details = angular.copy(data);
                });
            };

            // 选中的零件变化后的回调
            $scope.$watch('orderObj.detailVOList.length', function () {
                setMaterialDesc();
            });

            /* wangcan:查询当前仓库和库区下面的零件相关数量 */
            $scope.$watch('detailInfo.headInfo.outLocation', function () {
                // 把当前页面用户填写的发货数量记录到全局变量，用于后面数量的回写
                for(var i = 0 ,len = materialList.length; i < len ;i++){
                    for(var j = 0, len1 = $scope.detailInfo.details.length; j < len1; j++){
                        if(materialList[i].materialsNo == $scope.detailInfo.details[j].materialsNo){
                            materialList[i].deliveryQty = $scope.detailInfo.details[j].deliveryQty;
                        }
                    }
                }
                if (!!$scope.detailInfo.headInfo.exchangeNo && !!$scope.detailInfo.headInfo.outLocation && $scope.tabFlag.type == 0 || $scope.detailInfo.headInfo.outLocation == '') {
                    var service = "device";
                    var reqUrl = "/giftticket/exchangeOut/materials/numInfos";
                    var param = {
                        exchangeNo: $scope.detailInfo.headInfo.exchangeNo,
                        warehouseCode: $scope.detailInfo.headInfo.outLocation,
                        areaCode: $scope.detailInfo.headInfo.outArea
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        var newMaterialsList = [];
                        for (var i = 0, len = materialList.length; i < len; i++) {
                            angular.forEach(resp.value, function (item) {
                                if (item.materialsNo === materialList[i].materialsNo) {
                                    if(item.enableNum > 0){
                                        var newMaterial = angular.copy(materialList[i]);
                                        newMaterial.realStockQty = item.realStockQty;
                                        newMaterial.shipOccupation = item.shipOccupation;
                                        newMaterial.intentOccupation = item.intentOccupation;
                                        newMaterial.enableNum = item.enableNum;
                                        newMaterial.isChecked = false
                                        newMaterialsList.push(newMaterial);
                                    }
                                }
                            });
                        }
                        newMaterialsList.forEach(item => {
                          if (item.applyQty > item.enableNum) {  //判断订单是否大于库存 决定出库数量
                              item.deliveryQty = item.enableNum
                          }else if(item.applyQty < item.enableNum){
                              item.deliveryQty = item.applyQty
                          }
                        });
                        $scope.detailInfo.details = angular.copy(newMaterialsList);
                    });
                } else if ($scope.tabFlag.type == 2) {
                    var service = "device";
                    var reqUrl = "/giftticket/exchangeOut/materials/numInfos";
                    var param = {
                        exchangeNo: $scope.detailInfo.headInfo.exchangeNo,
                        warehouseCode: $scope.detailInfo.headInfo.outLocation,
                        areaCode: $scope.detailInfo.headInfo.outArea
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        for (var i = 0, len = $scope.detailInfo.details.length; i < len; i++) {
                            angular.forEach(resp.value, function (item) {
                                if (item.materialsNo === $scope.detailInfo.details[i].materialsNo) {
                                    $scope.detailInfo.details[i].realStockQty = item.realStockQty;
                                    $scope.detailInfo.details[i].shipOccupation = item.shipOccupation;
                                    $scope.detailInfo.details[i].intentOccupation = item.intentOccupation;
                                    $scope.detailInfo.details[i].enableNum = item.enableNum;
                                }
                            });
                        }
                    });
                }
            });

            $scope.$watch('detailInfo.headInfo.outArea', function () {

                // 把当前页面用户填写的发货数量记录到全局变量，用于后面数量的回写
                for(var i = 0 ,len = materialList.length; i < len ;i++){
                    for(var j = 0, len1 = $scope.detailInfo.details.length; j < len1; j++){
                        if(materialList[i].materialsNo == $scope.detailInfo.details[j].materialsNo){
                            materialList[i].deliveryQty = $scope.detailInfo.details[j].deliveryQty;
                        }
                    }
                }
                if (!!$scope.detailInfo.headInfo.exchangeNo && !!$scope.detailInfo.headInfo.outLocation && $scope.tabFlag.type == 0) {
                    var service = "device";
                    var reqUrl = "/giftticket/exchangeOut/materials/numInfos";
                    var param = {
                        exchangeNo: $scope.detailInfo.headInfo.exchangeNo,
                        warehouseCode: $scope.detailInfo.headInfo.outLocation,
                        areaCode: $scope.detailInfo.headInfo.outArea
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        var newMaterialsList = [];
                        for (var i = 0, len = materialList.length; i < len; i++) {
                            angular.forEach(resp.value, function (item) {
                                if (item.materialsNo === materialList[i].materialsNo) {
                                    if(item.enableNum > 0){
                                        var newMaterial = angular.copy(materialList[i]);
                                        newMaterial.realStockQty = item.realStockQty;
                                        newMaterial.shipOccupation = item.shipOccupation;
                                        newMaterial.intentOccupation = item.intentOccupation;
                                        newMaterial.enableNum = item.enableNum;
                                        newMaterial.isChecked = false
                                        newMaterialsList.push(newMaterial);
                                    }
                                }
                            });
                        }
                        newMaterialsList.forEach(item => {
                            if (item.applyQty > item.enableNum) {  //判断订单是否大于库存 决定出库数量
                                item.deliveryQty = item.enableNum
                            }else if(item.applyQty < item.enableNum){
                                item.deliveryQty = item.applyQty
                            }
                          });
                        $scope.detailInfo.details = angular.copy(newMaterialsList);
                    });
                } else if ($scope.tabFlag.type == 2) {
                    var service = "device";
                    var reqUrl = "/giftticket/exchangeOut/materials/numInfos";
                    var param = {
                        exchangeNo: $scope.detailInfo.headInfo.exchangeNo,
                        warehouseCode: $scope.detailInfo.headInfo.outLocation,
                        areaCode: $scope.detailInfo.headInfo.outArea
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        for (var i = 0, len = $scope.detailInfo.details.length; i < len; i++) {
                            angular.forEach(resp.value, function (item) {
                                if (item.materialsNo === $scope.detailInfo.details[i].materialsNo) {
                                    $scope.detailInfo.details[i].realStockQty = item.realStockQty;
                                    $scope.detailInfo.details[i].shipOccupation = item.shipOccupation;
                                    $scope.detailInfo.details[i].intentOccupation = item.intentOccupation;
                                    $scope.detailInfo.details[i].enableNum = item.enableNum;
                                }
                            });
                        }
                    });
                }
            });

            function setMaterialDesc() {
                angular.forEach($scope.detailInfo.details, function (item) {
                    item.materialNo = item.materialsNo ? item.materialsNo : item.materialNo;
                    item.materialsDes = item.materialsDes ? item.materialsDes : item.materialDes;
                });
            }


            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.details.length; i < len; i++) {
                    if (!!$scope.detailInfo.details[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.details.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.details[i].isChecked) {
                            $scope.detailInfo.details.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.details.length === 0) {
                        $scope.detailInfo.allCheckedMaterial = false;
                    }
                });
            };

            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/giftticket/exchangeOut/delete";
                var billIds = '';
                if (delType === "single") {
                    billIds = billId;
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            if (!!billIds) {
                                billIds = billIds + ',' + $scope.dataList[i].id;
                            } else {
                                billIds = $scope.dataList[i].id;
                            }
                        }
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get(service, reqUrl, {
                        ids: billIds
                    }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };
            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "GiftOut"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    $scope.detailInfo.headInfo.outArea = "";
                    angular.forEach($scope.detailInfo.details, function (item) {
                        item.stockLocation = "";
                        item.isChecked = false;
                        // 选择库区后 展示零件的默认储位
                        var locationList = item.stockLocationList || [];
                        for (var j = 0; j < locationList.length; j++) {
                            if (data.warehouseCode == locationList[j].warehouseCode) {
                                item.locationCode = locationList[j].locationCode;
                                break;
                            }
                        }
                    });
                    $scope.detailInfo.headInfo.outLocation = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.headInfo.outLocation = "";
                $scope.detailInfo.headInfo.outArea = "";
                angular.forEach($scope.detailInfo.details, function (item) {
                    item.stockLocation = "";
                    // 清除仓库后 同时清除 默认储位
                    item.locationCode = "";
                });
            };

            $scope.selectArea = function (type) {
                if (!$scope.detailInfo.headInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择调出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.headInfo.outLocation;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.headInfo.outArea = data.areaCode;
                    $scope.isThreeGuaranteesNegative = data.isThreeGuaranteesNegative === 1;
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.headInfo.outArea = "";
            };

            /* 获取兑换出库单详情 */
            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/giftticket/exchangeOut/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editData = function (item) {
                $scope.editDataId = item.id;
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.details, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        checkItemStockStatus(item, item.deliveryQty);
                    });
                    $scope.changeTab(2);
                })
            };

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;

                    angular.forEach($scope.detailInfo.details, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                    });
                    $scope.changeTab(3);
                })
            }

            $scope.checkQty = function (item) {
                item.deliveryQtyErr = false;
                if (item.deliveryQty === "") {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "出库数量不能为空";
                    return;
                }
                if (item.deliveryQty > 99999.999) {
                    item.deliveryQty = 99999.999;
                }
                if (parseFloat(item.deliveryQty) > ybWidget.Minus(item.applyQty, item.issuedQty)) {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "出库数量不能大于剩余数量";
                    return;
                }
                checkItemStockStatus(item, item.deliveryQty)
            };

            function checkItemStockStatus(item, currentQty) {
                if ($scope.isThreeGuaranteesNegative) return; // 选择了允许负库存的库区，不再做数量校验
                UserContextService.SetStockStatusFlag(item, currentQty);
            }

            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    item.showStockErr = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };


            $scope.saveData = function (isValid, status) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                if (!!$scope.detailInfo && $scope.detailInfo.details.length === 0) {
                    ybWidget.ShowMessage("无零件时无法提交", MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/giftticket/exchangeOut/add";
                var param = angular.copy($scope.detailInfo);
                param.status = status;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };


            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.detailInfo.details.length; i < len; i++) {
                    if (!$scope.detailInfo.details[i].deliveryQty || $scope.detailInfo.details[i].deliveryQty === '0') {
                        isValid = false;
                        $scope.detailInfo.details[i].deliveryQtyErr = true;
                        $scope.detailInfo.details[i].deliveryQtyErrMsg = "出库数量不能为空或0";
                        break;
                    }
                    if (parseFloat(!$scope.detailInfo.details[i].deliveryQty) > ybWidget.Minus(!$scope.detailInfo.details[i].applyQty, !$scope.detailInfo.details[i].issuedQty)) {
                        item.deliveryQtyErr = true;
                        item.deliveryQtyErrMsg = "出库数量不能大于剩余数量";
                        return;
                    }
                }
                return isValid;
            }
            $scope.outboundStatus = [
                {id: 0, name: "未出库"},
                {id: 1, name: "部分出库"},
                {id: 2, name: "已出库"}
            ];

            /* 上一步 */
            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            /* ----------------------出库、结单--------------------------- */

            //出库
            $scope.outbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    $scope.changeTab(4);
                });
            };

            /* 选择储位 */
            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.headInfo.outLocation
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.locationCode = data.locationCode; // 本条零件的储位
                })
            };

            // 批量选择储位
            $scope.multiSelDepot = function () {
                var warehouseCode = $scope.detailInfo.headInfo.outLocation;
                var list = $scope.detailInfo.details;
                MaterialService.multiSelDepot(warehouseCode, list);
            };

            $scope.clearDepot = function (item) {
                item.locationCode = "";
            };

            /* 出库操作提交 */
            $scope.outboundSubmit = function () {
                var haslocationCode = $scope.detailInfo.details.every(function (item) {
                    return !!item.locationCode
                });
                if (!haslocationCode) {
                    ybWidget.ShowMessage("请选择储位", MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.headInfo.exchangeOutNo;
                angular.forEach($scope.detailInfo.details, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.locationCode = item.locationCode;
                    param.detailList.push(listRow);
                });
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };


            /* 结单 */
            $scope.mandatoryFinish = function (exchangeOutNo, billId, materialsNo) { // 出库单号、单据id和零件编号
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/giftticket/exchangeOut/manualFinish";
                    var param = {
                        exchangeOutNo: exchangeOutNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;

                                angular.forEach($scope.detailInfo.details, function (item) {
                                    item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                                });
                            });
                        }
                        getDataList();
                    });
                });
            };

            (function () {
                window.sessionStorage.removeItem("storageRecordsId");
                if (!!$stateParams.id) {
                    $scope.tabFlag.type = 0;
                    $scope.changeTab(1);
                    $scope.selBill($stateParams)
                } else {
                    getDataList();
                    $scope.setFixedWidth();
                }
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
